package com.cskaoyan.service;

import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.po.*;
import com.cskaoyan.bean.vo.WxCouponListInnerVO;
import com.cskaoyan.bean.vo.WxCouponSelectlistInnerVO;
import com.cskaoyan.bean.vo.WxMylistInnerVO;
import com.cskaoyan.mapper.MarketCartMapper;
import com.cskaoyan.mapper.MarketCouponMapper;
import com.cskaoyan.mapper.MarketCouponUserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @author zhuqiushi
 * @since 2022/09/08 16:37
 */
@Service
public class WxCouponServiceImpl implements WxCouponService {
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    MarketCartMapper marketCartMapper;

    @Override
    public CommonData<WxCouponListInnerVO> list(Integer page, Integer limit) {
        //查询优惠券做分页后返回
        //分页
        PageHelper.startPage(page, limit);
        MarketCouponExample marketCouponExample = new MarketCouponExample();
        //加一个筛选deleted，加一个筛选可用优惠券
        marketCouponExample.createCriteria()
                .andDeletedEqualTo(false)
                .andStatusEqualTo((short) 0);
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);
        CommonData result = CommonData.data(new PageInfo(marketCoupons));
        LinkedList<WxCouponListInnerVO> wxCouponListInnerVOS = new LinkedList<>();
        for (MarketCoupon marketCoupon : marketCoupons) {
            WxCouponListInnerVO temple = new WxCouponListInnerVO();
            BeanUtils.copyProperties(marketCoupon, temple);
            wxCouponListInnerVOS.add(temple);
        }

        result.setList(wxCouponListInnerVOS);
        return result;
    }

    @Override
    public CommonData<WxMylistInnerVO> mylist(Short status, Integer page, Integer limit, Integer userId) {
        //查询自己的优惠券后返回
        //分页
        PageHelper.startPage(page, limit);
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        marketCouponUserExample.createCriteria()
                .andDeletedEqualTo(false)
                .andUserIdEqualTo(userId)
                .andStatusEqualTo(status);
        //查询
        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
        CommonData result = CommonData.data(new PageInfo(marketCouponUsers));
        //做一个循环赋值
        LinkedList<WxMylistInnerVO> wxMylistInnerVOS = new LinkedList<>();
        for (MarketCouponUser marketCouponUser : marketCouponUsers) {
            //查coupon表
            WxCouponSelectlistInnerVO selectlistInnerVO =
                    getWxCouponSelectlistInnerVOByMarketCouponUser(marketCouponUser);
            WxMylistInnerVO temple = new WxMylistInnerVO();
            BeanUtils.copyProperties(selectlistInnerVO, temple);
            wxMylistInnerVOS.add(temple);
        }
        result.setList(wxMylistInnerVOS);
        return result;
    }

    /*
     * market-coupon表中的status 0-正常可用；1-过期; 2-已下架。
     * market-user-coupon表中的status 0-未使用；1-已使用；2-已过期；3-已经下架；',
     * */
    @Override
    public int receive(Integer userId, Integer couponId) {
        //receive就是往优惠券user表中加数据
        //先查coupon表
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);
        MarketCouponUser marketCouponUser = getMarketCouponUserByMarketCoupon(userId, marketCoupon);
        if (marketCouponUser == null) return 400;
        //插入coupon-user表
        marketCouponUserMapper.insertSelective(marketCouponUser);
        return 0;
    }

    @Override
    public CommonData<WxCouponSelectlistInnerVO> selectlist(Integer cartId, Integer grouponRulesId, Integer userId) {
        PageHelper.startPage(1, 4);
        LinkedList<WxCouponSelectlistInnerVO> targetInnerVOs = new LinkedList<>();
        //先根据cartId查购物车
        MarketCart marketCart = marketCartMapper.selectByPrimaryKey(cartId);
        /*
         * 暂不知道grouponRulesId是干啥的？  不用管
         * */
        //再查coupon-user表，查出有哪些优惠券可以用
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        marketCouponUserExample.createCriteria().andUserIdEqualTo(userId);
        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
        //再根据这些优惠券去coupon表查详情
        for (MarketCouponUser singleCouponUser : marketCouponUsers) {
            WxCouponSelectlistInnerVO wxCouponSelectlistInnerVO = getWxCouponSelectlistInnerVOByMarketCouponUser(singleCouponUser);
            targetInnerVOs.add(wxCouponSelectlistInnerVO);
        }
        CommonData result = CommonData.data(new PageInfo(marketCouponUsers));
        result.setList(targetInnerVOs);
        return result;
    }

    @Transactional
    @Override
    public int exchange(String code, Integer userId) {
        MarketCouponExample marketCouponExample = new MarketCouponExample();
        marketCouponExample.createCriteria()
                .andCodeEqualTo(code)
                .andStatusEqualTo((short) 0)
                .andDeletedEqualTo(false);
        //先查coupon表
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);
        if (!(marketCoupons.size() > 0)) {
            return 742;
        }
        //新增优惠券
        MarketCouponUser marketCouponUser = getMarketCouponUserByMarketCoupon(userId, marketCoupons.get(0));
        marketCouponUserMapper.insertSelective(marketCouponUser);
        return 0;
    }

    private MarketCouponUser getMarketCouponUserByMarketCoupon(Integer userId,
                                                               MarketCoupon marketCoupon) {
        Date date = new Date(System.currentTimeMillis());
        MarketCouponUser marketCouponUser = new MarketCouponUser();
        BeanUtils.copyProperties(marketCoupon, marketCouponUser);
        //赋值用户id
        marketCouponUser.setCouponId(marketCoupon.getId());
        marketCouponUser.setUserId(userId);
        marketCouponUser.setId(null);
        //给status赋值
        if (marketCoupon.getStatus().intValue() == 0 && !marketCoupon.getDeleted()) {
            marketCouponUser.setStatus((short) 0);
        } else {
            //说明优惠券已经不可用
            return null;
        }
        //给time赋值
        if (marketCoupon.getTimeType()==0) {
            //说明是根据days加
            marketCouponUser.setStartTime(date);
            marketCouponUser.setEndTime(addDateTime(date,marketCoupon.getDays(),0,0));
        }
        marketCouponUser.setAddTime(date);
        marketCouponUser.setUpdateTime(date);
        return marketCouponUser;
    }

    private WxCouponSelectlistInnerVO getWxCouponSelectlistInnerVOByMarketCouponUser(MarketCouponUser singleCouponUser) {
        Date date = new Date(System.currentTimeMillis());
        WxCouponSelectlistInnerVO wxCouponSelectlistInnerVO = new WxCouponSelectlistInnerVO();
        wxCouponSelectlistInnerVO.setAvailable(true);
        //在此判断该用户优惠券是否不能用了
        if (singleCouponUser.getDeleted() || singleCouponUser.getStatus().intValue() != 0 || (singleCouponUser.getEndTime() != null && singleCouponUser.getEndTime().before(date))) {
            wxCouponSelectlistInnerVO.setAvailable(false);
        }
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(singleCouponUser.getCouponId());
        /*
         * 在此做coupon是否能用的判断
         * */
       /* if (marketCoupon.getDeleted()) {
            //说明该优惠券可用
            wxCouponSelectlistInnerVO.setAvailable(false);
        }*/
        //给新对象赋值
        BeanUtils.copyProperties(marketCoupon, wxCouponSelectlistInnerVO);
        wxCouponSelectlistInnerVO.setId(singleCouponUser.getId());
        wxCouponSelectlistInnerVO.setCid(marketCoupon.getId());
        return wxCouponSelectlistInnerVO;
    }
    /**
     * 给时间date加上天数，小时，分钟
     * @param date   //需要加的时间
     * @param day    //要加的天数
     * @param hour   //要加的小时
     * @param minute //要加的分钟
     * 返回date
     */
    private   Date addDateTime(Date date, int day, int hour, int minute) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, day);// 24小时制,加天
        cal.add(Calendar.HOUR, hour);// 24小时制 ,加小时
        cal.add(Calendar.MINUTE, minute);// 24小时制,加分钟
        date = cal.getTime();
        return date;
    }

}
